<?php
/**
 * Push报表基础类(数据库模型)
 *   
 * @author wenqiang@6rooms.com
 * @version $Id: Base.class.php,v 1.0 2013/11/28 16:45:42 gaowenqiang Exp $   
 * @package sr.model.report.push
 *
 */
class Sr_Model_Report_Push_Base extends Sr_Model_Base
{
	const STAT_TYPE_DAY = 1;// 按天统计
	const STAT_TYPE_HOUR = 2;// 按小时统计
	const STAT_TYPE_HALFHOUR = 3;// 按半小时统计
	
	/**
	 * 构造器
	 *
	 * @var array
	 */
	public function __construct($args = null)
	{
		parent::__construct($args);

		$this->initExpr();
	}

	/**
	 * 初始化表达式数据
	 *
	 */
	protected function initExpr()
	{
		if (empty($this->expr)) {
			$this->expr = array(
				// 发送成功
				'COUNT_SUCCESS' => "SUM(success_num)",
				// 发送失败
				'COUNT_FAIL' => "SUM(fail_num)",
				// 未处理
				'COUNT_PENDING' => "SUM(pending_num)",
				// 平均发送时间(成功)
				'AVG_SPEND_TIME_SUCCESS' => "SUM(success_stime) / SUM(success_num)",
				// 平均发送时间(失败)
				'AVG_SPEND_TIME_FAIL' => "SUM(fail_stime) / SUM(fail_num))",
				// 平均发送时间(成功+失败)
				'AVG_SPEND_TIME' => "SUM(success_stime + fail_stime) / SUM(success_num + fail_num)",
			);
		}
	}
	
	/*
	 * 生成查询条件
	 *
	 * @param array $cond 查询条件
	 *  'prod' int 产品id
	 *  'start' string 开始时间
	 *  'end' string 结束时间
	 * @return string
	 */
	protected function where($cond)
	{
		$where = array();
		if (isset($cond['start']) && strlen($cond['start']) &&
				isset($cond['end']) && strlen($cond['end']))
		{
			$where[] = "source_ts >= '{$cond['start']}' AND source_ts <= '{$cond['end']}'";
		}

		if (isset($cond['prod']) && $cond['prod'] > 0)
		{
			$where[] = "prod = {$cond['prod']}";
		}

		return count($where) ? implode(' AND ', $where) : null;
	}

	/**
	 * 获取列表数据
	 *
	 * @param array $cond
	 *  'prod' int 产品id
	 *  'start' string 开始时间
	 *  'end' string 结束时间
	 * @return array
	 */
	public function getList($cond)
	{
		$column = '*';
		$from = $this->name;
		$where = $this->where($cond);
		$order = 'source_ts DESC';
		$sql = $this->sql($column, $from, $where, null, $order);

		return $this->fetchAll($sql);
	}
	
	/**
	 * 获取列表统计数据
	 *
	 * @param array $cond
	 *  'prod' int 产品id
	 *  'start' string 开始时间
	 *  'end' string 结束时间
	 * @return array
	 */
	public function getTotal($cond)
	{
		$column = $this->column(array(
			'COUNT_SUCCESS',
			'AVG_SPEND_TIME_SUCCESS',
			'COUNT_FAIL',
			'AVG_SPEND_TIME_FAIL',
			'COUNT_PENDING'
		));
		$from = $this->name;
		$where = $this->where($cond);
		$order = 'source_ts DESC';
		$sql = $this->sql($column, $from, $where, null, $order);

		return $this->fetchAll($sql);
	}

}
